package com.handu.luna.boss.controller;

import com.handu.luna.core.domain.promotion.*;
import com.handu.luna.core.domain.search.BonusPromotionSearch;
import com.handu.luna.core.domain.user.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * Created by wangzailiang on 2014/6/20.
 */
@Controller
@RequestMapping("/promotion/cashcard/*")
public class CashCardPromotionController extends BaseController {


    @RequestMapping(value = "index",method = RequestMethod.GET)
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        BonusPromotionSearch bonusPromotionSearch;
        BossModel bossModel = createModel("promotion/cashcard/index");
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			bonusPromotionSearch = (BonusPromotionSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), BonusPromotionSearch.class);
		}else{
			bonusPromotionSearch = new BonusPromotionSearch();
            viewState = "";
		}
        return bossModel
                .add("cashCardPromotionPage", new CashCardPromotion().findAll(CashCardPromotion.selectCondition(bonusPromotionSearch),pageable))
                .add("bonusPromotionSearch", bonusPromotionSearch)
                .add("grantTypeList", CashCardPromotion.grantTypeValues())
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", viewState);
    }

    @RequestMapping(value = "index",method = RequestMethod.POST)
    public BossModel index(BonusPromotionSearch bonusPromotionSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        BossModel bossModel = createModel();
        return bossModel
                .add("cashCardPromotionPage", new CashCardPromotion().findAll(CashCardPromotion.selectCondition(bonusPromotionSearch),pageable))
                .add("cashCardPromotionSearch", bonusPromotionSearch)
                .add("grantTypeList", CashCardPromotion.grantTypeValues())
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(bonusPromotionSearch).toString().getBytes("UTF-8")));
    }

    @RequestMapping(value = "grant/{cashCardPromotionId}")
    public BossModel grant(@PathVariable Long cashCardPromotionId) {

        return getGrantModel(cashCardPromotionId);

    }

    @RequestMapping(value = "grant_userRank")
    public BossModel grant_userRank(Long cashCardPromotionId, Long userRankId,RedirectAttributes redirectAttributes) {
        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);

        long grantNum = new CashCard().saveByUserRankId(userRankId,cashCardPromotionId);
        if(grantNum > 0) {
            redirectAttributes.addFlashAttribute("message", "成功发放现金卡\t"+cashCardPromotion.getName() +"\t"+ grantNum +"张");
        }
        return createModel("redirect:index");
    }

    @RequestMapping(value = "userSearch",produces = {"application/json;charset=UTF-8"})
    public  @ResponseBody
    String userSearch(@RequestParam(value = "username", required = false) String username) {

        List<User> userList = context.getUserRepository().findByNameLike("%"+username+"%");
        JSONArray jsonArray = JSONArray.fromObject(userList);
        return jsonArray.toString();
    }


    @RequestMapping(value = "grant_user")
    public BossModel grant_user(Long cashCardPromotionId, Long[] userIdArray,RedirectAttributes redirectAttributes) {
        if(null == userIdArray) {
            return createModel("redirect:index");
        }
        List<Long> userIdList = new ArrayList<>();
        for(Long userid : userIdArray) {
            userIdList.add(userid);
        }
        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);
        long grantNum = new CashCard().saveByUsersId(userIdList,cashCardPromotionId);

        redirectAttributes.addFlashAttribute("message", "成功发放现金卡\t"+cashCardPromotion.getName() +"\t"+ grantNum +"张");
        return createModel("redirect:index");
    }

    @RequestMapping(value = "grant_underline")
    public BossModel grant_underline(Long grantNum,Long cashCardPromotionId,RedirectAttributes redirectAttributes) {

        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);

        new CashCard().save(cashCardPromotionId,grantNum);
        redirectAttributes.addFlashAttribute("message", "成功发放现金卡\t"+ cashCardPromotion.getName()+"\t"+grantNum+"张");
        return createModel("redirect:index");
    }

    @RequestMapping(value = "view/index/{cashCardPromotionId}")
    public BossModel view(@PathVariable Long cashCardPromotionId,String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        String state = "";
        if(viewState != null) {
            state = viewState;
        }
        return createModel("/promotion/cashcard/view/index")
                .add("cashCardPromotionId",cashCardPromotionId)
                .add("cashCardPage", new CashCard().findAllByCashCardPromotionId(cashCardPromotionId,pageable))
                .add("viewState",state);
    }

    @RequestMapping(value = "log/index/{cashCardPromotionId}/{cashCardId}")
    public BossModel log(@PathVariable Long cashCardPromotionId,@PathVariable Long cashCardId) {


        return createModel("/promotion/cashcard/log/index")
                .add("cashCardPromotionId",cashCardPromotionId)
                .add("cashCardLogList", context.getCashCardLogRepository().findAll(cashCardId));
    }

    @RequestMapping(value = "export/{cashCardPromotionId}")
    public BossModel export(@PathVariable Long cashCardPromotionId,HttpServletResponse response) {

        CashCardPromotion cashCardPromotion = new CashCardPromotion().findOne(cashCardPromotionId);

        HSSFWorkbook wb = new CashCard().getExcelModel(cashCardPromotionId);

        //String  mimetype = "application/x-msdownload";
        String fileName = cashCardPromotion.getName();
        //String inlineType = "attachment";
        try {
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1" ) + ".xls\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value="add",method = RequestMethod.GET)
    public BossModel add() {

        CashCardPromotion cashCardPromotion = new CashCardPromotion();
        List<BonusPromotion.UseRange> useRangeList = new ArrayList<>();
        useRangeList.add(BonusPromotion.UseRange.WEBSITE);
        cashCardPromotion.setUseRangeList(useRangeList);
        cashCardPromotion.setGrantType(BonusPromotion.GrantType.USER);

        return getEditModel(cashCardPromotion);
    }

    @RequestMapping(value="edit/{id}",method = RequestMethod.GET)
    public BossModel edit(@PathVariable Long id) {

        CashCardPromotion cashCardPromotion = new CashCardPromotion().findOne(id);

        return getEditModel(cashCardPromotion);
    }

    @RequestMapping(value="save",method = RequestMethod.POST)
    //@InitBinder(value = {"name","bonusPrice","limitPrice","grantType","grantStartDate","grantEndDate","useStartDate","useEndDate","remark","grantLimitPrice","goodsIds","useRanges"})
    public BossModel save(@Valid final CashCardPromotion cashCardPromotion, final BindingResult bindingResult, RedirectAttributes redirectAttributes) {

        if(null == cashCardPromotion.getGrantStartDate()) {
            bindingResult.rejectValue("grantStartDate","","发放开始时间不能为空");
        }
        if(null == cashCardPromotion.getGrantEndDate()) {
            bindingResult.rejectValue("grantEndDate","","发放结束时间不能为空");
        }
        if(null == cashCardPromotion.getUseStartDate()) {
            bindingResult.rejectValue("useStartDate","","使用开始时间不能为空");
        }
        if(null == cashCardPromotion.getUseEndDate()) {
            bindingResult.rejectValue("useEndDate","","使用结束时间不能为空");
        }
        if(null != cashCardPromotion.getGrantStartDate() && null !=cashCardPromotion.getGrantEndDate()) {
            if(cashCardPromotion.getGrantStartDate().compareTo(cashCardPromotion.getGrantEndDate()) != -1) {
                bindingResult.rejectValue("grantStartDate","","发放开始时间必须小于发放结束时间");
            }
        }
        if(null != cashCardPromotion.getUseStartDate() && null !=cashCardPromotion.getUseEndDate()) {
            if(cashCardPromotion.getUseStartDate().compareTo(cashCardPromotion.getUseEndDate()) != -1) {
                bindingResult.rejectValue("useStartDate","","使用开始时间必须小于使用结束时间");
            }
        }
        if(null != cashCardPromotion.getGrantStartDate() && null !=cashCardPromotion.getUseStartDate()) {
            if(cashCardPromotion.getGrantStartDate().compareTo(cashCardPromotion.getUseStartDate()) != -1) {
                bindingResult.rejectValue("grantStartDate","","发放开始时间必须小于使用开始时间");
            }
        }
        if(null == cashCardPromotion.getUseRangeList() || cashCardPromotion.getUseRangeList().size() == 0) {
            bindingResult.rejectValue("useRangeList","","至少选择一项");
        }

        if(bindingResult.hasErrors()) {
            return getEditModel(cashCardPromotion);
        }
        redirectAttributes.addFlashAttribute("message", cashCardPromotion.getSucessFlashMessage("现金卡类型"));
        cashCardPromotion.save(cashCardPromotion);
        return createModel("redirect:index");
    }

    @RequestMapping(value="delete",method= RequestMethod.POST)
    public BossModel delete(String viewState,Long cashCardPromotionId,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
        context.getCashCardPromotionRepository().delete(cashCardPromotionId);
        context.getCashCardRepository().deleteByBonusPromotionId(cashCardPromotionId);
        return createModel("/promotion/cashcard/cashcardpromotion_table")
                .add("cashCardPromotionPage",new CashCardPromotion().findAll(null,pageable))
                .add("viewState",viewState);
    }

    @RequestMapping(value="deleteCashCard",method= RequestMethod.POST)
    public BossModel deleteCashCard(String viewState,Long id,Long cashCardPromotionId,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
        new CashCard().delete(id,cashCardPromotionId);
        return createModel("/promotion/cashcard/view/cashcard_table")
                .add("cashCardPromotionId",cashCardPromotionId)
                .add("cashCardPage", new CashCard().findAllByCashCardPromotionId(cashCardPromotionId,pageable))
                .add("viewState",viewState);
    }

    public BossModel getEditModel(CashCardPromotion cashCardPromotion) {

        return createModel("/promotion/cashcard/info")
                .add("cashCardPromotion", cashCardPromotion)
                .add("brandList", context.getBrandRepository().findAll())
                .add("useRangeValues", CashCardPromotion.UseRange.values())
                .add("grantTypeList", CashCardPromotion.grantTypeValues());
    }

    /**
     * 根据发放类型选择视图
     * @param cashCardPromotionId
     * @return
     */
    private BossModel getGrantModel(Long cashCardPromotionId) {

        CashCardPromotion cashCardPromotion = new CashCardPromotion().findOne(cashCardPromotionId);

        BossModel bossModel = null;
        switch (cashCardPromotion.getGrantType()) {
            case USER :
                bossModel = createModel("/promotion/cashcard/grant/grant_user")
                        .add("userRankList",context.getUserRankRepository().findAll())
                        .add("userList",context.getUserRepository().findAll())
                        .add("cashCardPromotion", cashCardPromotion)
                        .add("userIdList",new ArrayList<Long>());
                break;
            case UNDERLINE:
                bossModel = createModel("/promotion/cashcard/grant/grant_underline")
                        .add("cashCardPromotion",cashCardPromotion);
                break;
            default:
                System.out.println("default");
        }

        return bossModel;

    }

    public BossModel getViewModel() {

        return createModel("/promotion/cashcard/view/index");
    }
}
